package com.demo.library.service.Impl;

import com.demo.library.Dao.BookRepository;
import com.demo.library.Dao.LogRepository;
import com.demo.library.config.RabbitMQConfig;
import com.demo.library.entity.Book;
import com.demo.library.entity.Log;
import com.demo.library.service.BookService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    private final BookRepository bookRepository;

    private final LogRepository logRepository;

    private final RabbitTemplate rabbitTemplate;

    public BookServiceImpl(BookRepository bookRepository, LogRepository logRepository, RabbitTemplate rabbitTemplate) {
        this.bookRepository = bookRepository;
        this.logRepository = logRepository;
        this.rabbitTemplate = rabbitTemplate;
    }

    @Override
    public List<Book> findAll() {
        return bookRepository.findAll();
    }

    @Override
    public Book findById(Long id) {
        return bookRepository.getById(id);
    }

    @Override
    public void save(Book book) {
        Log log = new Log();
        log.setInfo("save book");
        log.setCreateTime(new Date());
        rabbitTemplate.convertAndSend(RabbitMQConfig.exchange, RabbitMQConfig.routingKey, log);
        bookRepository.save(book);

    }

    @Override
    public void update(Book book) {
        Log log = new Log();
        log.setInfo("修改书籍");
        log.setCreateTime(new Date());
        rabbitTemplate.convertAndSend(RabbitMQConfig.exchange, RabbitMQConfig.routingKey, log);
        bookRepository.save(book);

    }

    @Override
    public void deleteById(Long id) {

        bookRepository.deleteById(id);
    }

    @Override
    public List<Book> findByTitle(String title) {
        return bookRepository.findByTitleContains(title.trim());
    }

    @Override
    public String getPublisherNameById(Long id) {
        Book book = bookRepository.getById(id);
        if (book != null) {
            return book.getPublisher().getPublisherName();
        }
        return null;
    }

    @Override
    public List<String> findAuthorList() {
        return bookRepository.getAuthorList();
    }

    @RabbitListener(queues = RabbitMQConfig.queue)
    public void receiveLog(Log log) {
        logRepository.save(log);
        System.out.println("接收到的日志信息：" + log);
    }

}
